package com.fatgirl.patterns.state.fsm
{
	import com.fatgirl.patterns.iterator.IIterator;
	import com.fatgirl.patterns.state.IStateControl;

	/**
	 * FSM状态机 基类
	 * 为一个组合元素 可以作为节点使用
	 * @author iceman
	 * 
	 */
	public class FSMStateMachine extends AbsFSMState
	{
		/**
		 * 当前状态 
		 */
		private var m_currentState:IFSMState;
		/**
		 * 默认状态 
		 */
		private var m_defaultState:IFSMState;
		/**
		 * 目标状态 
		 */
		private var m_goalState:IFSMState;
		
		/**
		 * 状态队列 
		 */
		private var m_states:Vector.<IFSMState>;
		
		/**
		 * 目标ID 
		 */
		private var m_goalID:int;
		
		/**
		 * 状态机构造 
		 * @param _type 状态机类型
		 * @param _controller 状态机控制器
		 * 
		 */
		public function FSMStateMachine(_type:int,_controller:IStateControl = null)
		{
			super(_type,_controller);
			m_states = new Vector.<IFSMState>;
		}
		/**
		 * 添加状态 
		 * @param _state
		 * 
		 */
		public override final function addItem(_state:IFSMState):void
		{
			_state.setParent(this);
			m_states.push(_state);
		}
		/**
		 * 设置默认状态 
		 * @param _state
		 * 
		 */
		public override final function setDefaultState(_state:IFSMState):void
		{
			m_defaultState = _state;
		}
		
		/**
		 * 获取默认状态 
		 * @return 
		 * 
		 */
		public override final function getDefaultState():IFSMState
		{
			return m_defaultState;
		}

		/**
		 * 状态变迁 
		 * @param _goal
		 * 
		 */
		public override final function transitionState(_goal:int):void
		{
			m_goalID = _goal;
			updateMachine();
		}
		/**
		 * 返回状态集迭代器 
		 * @param _type 目前对类型不做处理
		 * @return 
		 * 
		 */
		public override final function iterator(_type:String=null):IIterator
		{
			return new FSMStateIterator(m_states);
		}
		/**
		 * 根据目标进行变迁 
		 * @param _goal 目标ID
		 * @return 返回变迁是否成功
		 * 
		 */
		private function checkTransitionState(_goal:int):Boolean
		{
			if(m_states.length==0)
			{
				return false;
			}
			for(var i:int = 0;i<m_states.length;i++)
			{
				if(m_states[i].getType() == _goal)
				{
					m_goalState = m_states[i];
					return true;
				}
			}
			return false;
		}
		/**
		 * 更新状态 
		 * 
		 */
		private function updateMachine():void
		{
			//没有状态返回
			if(m_states.length==0)
			{
				return;
			}
			if(!m_currentState)
			{
				m_currentState = m_defaultState;
			}
			if(!m_currentState)
			{
				return;
			}
			var t_oldStateID:int = m_currentState.getType();
			
			//检查是否应该变迁
			if(m_goalID != t_oldStateID)
			{
				if(checkTransitionState(m_goalID))
				{
					m_currentState.exit();
					m_currentState = m_goalState;
					m_currentState.enter();
				}
				else
				{
					throwError(this,FatError.NO_FOUND_STATE_OBJ+m_goalID);
				}
			}
			m_currentState.update();
			
		}
			
	}
}